<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
// use App\Utils\JWT\Control as JWT;
use App\Common\Enum\Attributes;
use App\Common\Enum\Header;

use App\Services\JWT\Server as JWTServer;

class AdminRefreshToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {

        return JWTServer::adminRefresh()->check(
            $request,
            Header::ADMIN_REFRESH_TOKEN,
            fn () => $next($request),//还没到过期时间
            function () use ($request, $next) {
                $loginInfo =  $request->get(Attributes::LOGIN_INFO->value);
                $request->attributes->add([Attributes::RES_HEADER->value => [
                  'ADMIN_LOGIN_TOKEN' => JWTServer::adminLogin()->create($loginInfo),  //过期后重新生成Token
                  'ADMIN_REFRESH_TOKEN' => JWTServer::adminRefresh()->create($loginInfo)  //刷新token
                ]]);  //设置响应头信息
                return $next($request);
            }
        );
    }
}
